package com.lsx143.wordcount.day5;

import com.lsx143.wordcount.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

public class Flink_TumblingWindowFunction {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env
                .socketTextStream("hadoop162", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String line, Collector<WaterSensor> out) throws Exception {
                        String[] datas = line.split(",");
                        out.collect(new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2])));
                    }
                })
                .keyBy(WaterSensor::getId)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<WaterSensor>() {
                            @Override
                            public WaterSensor reduce(WaterSensor w1, WaterSensor w2) throws Exception {
                                w1.setVc(w1.getVc() + w2.getVc());
                                System.out.println("Flink_TumblingWindowFunction.reduce");
                                return w1;
                            }
                        },
                        new WindowFunction<WaterSensor, String, String, TimeWindow>() {
                            @Override
                            public void apply(String key,
                                              TimeWindow window,
                                              Iterable<WaterSensor> input,
                                              Collector<String> out) throws Exception {
                                out.collect(window + " , " + input.iterator().next().toString());
                            }
                        }
                )
                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}